import Vue from "vue";
import messageBoxVue from "../index";

const defaultMessage = {
  loading: "正在拼了全站流量给您加载..."
};
const messageBox = Vue.extend(messageBoxVue);
let count = 1;

function filterOptions(options) {
  let newO = {};
  switch (typeof options) {
    case "string":
    case "number":
      newO.message = options;
      break;
    case "object":
      newO = options;
      break;
  }
  return newO;
}
const Message = options => {
  if (Vue.prototype.$isServer) return;
  // eslint-disable-next-line new-cap
  const $messageBox = new messageBox();
  Object.assign($messageBox, filterOptions(options));
  $messageBox.vm = $messageBox.$mount();
  $messageBox.id = `message_${count++}`;
  $messageBox.dom = $messageBox.vm.$el;
  document.body.appendChild($messageBox.dom);
  Message.close = function() {
    $messageBox.closeNotify();
  };
  return $messageBox;
};

["success", "warning", "info", "error"].forEach(type => {
  Message[type] = options => {
    options = filterOptions(options);
    options.type = type;
    return Message(options);
  };
});

Message.loading = function(options) {
  const defaultOptions = {
    type: "loading",
    message: "",
    duration: 0
  };
  const optionType = typeof options;
  if (["string", "number"].includes(optionType)) {
    defaultOptions.message = options;
  } else if (optionType === "object") {
    defaultOptions.message = options.message || defaultMessage["loading"];
  } else {
    defaultOptions.message = defaultMessage["loading"];
  }
  Object.assign(defaultOptions, filterOptions(options));
  if (!defaultOptions.message)
    defaultOptions.message = defaultMessage["loading"];
  return Message(defaultOptions);
};

export default Message;
